﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;
#if UNITY_EDITOR
using UnityEditor;
#endif

[RequireComponent(typeof(Tilemap))]
[ExecuteInEditMode]
public class BlockTileManager : MonoBehaviour
{
    [HideInInspector]
    public Tilemap tileMap;

    public Dictionary<Vector3Int, Tile> tilesResDict;
    public Dictionary<Vector3Int, Matrix4x4> transformDict;
    [ReadOnly]
    public int dataSize = 0;

    // Start is called before the first frame update
    void Start()
    {
        tileMap = this.gameObject.GetComponent<Tilemap>();
    }

    public void ClearAll()
    {
        CalculateRes();
        tileMap.ClearAllTiles();
    }

    public void ShowAtPos(int x,int y)
    {
        Vector3Int key = new Vector3Int(x, y, 0);
        if(tilesResDict!=null && tilesResDict.ContainsKey(key))
        {
            tileMap.SetTile(key, tilesResDict[key]);
            tileMap.SetTransformMatrix(key, transformDict[key]);
        }
    }

    private void CalculateRes()
    {
        tilesResDict = new Dictionary<Vector3Int, Tile>();
        transformDict = new Dictionary<Vector3Int, Matrix4x4>();
        foreach (var position in tileMap.cellBounds.allPositionsWithin)
        {
            // Do stuff per position
            Tile tile = tileMap.GetTile<Tile>(position);
            if (tile)
            {
                tilesResDict[position] = tile;
                transformDict[position] = tileMap.GetTransformMatrix(position);
            }
        }
    }
}

#if UNITY_EDITOR
[CustomEditor(typeof(BlockTileManager))]
public class BlockTileManagerEditor : Editor
{
    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();

        if (GUILayout.Button("Calculate Tile Sprite"))
        {
            var t = (BlockTileManager)target;
            t.tilesResDict = new Dictionary<Vector3Int, Tile>();
            Debug.Log("Map Bounds:"+t.tileMap.cellBounds.center);
            Debug.Log("Map Bounds:" + t.tileMap.cellBounds.size);

            //TileBase[] ts = t.tileMap.GetTilesBlock(t.tileMap.cellBounds);
            //Debug.Log("Tiles Count:" + ts.Length);

            int i = 0;
            foreach (var position in t.tileMap.cellBounds.allPositionsWithin)
            {
                // Do stuff per position
                Tile tile = t.tileMap.GetTile<Tile>(position);
                if(tile)
                {
                    Debug.Log(i + " " + position + " " + tile.sprite.name);
                    t.tilesResDict[position] = tile;
                    i++;
                }
            }
            t.dataSize = i + 1;
        }
    }
}
#endif